package com.example.xd.defaultcall.test;

import android.os.Looper;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * @auther XuDan on 2020/6/29.
 */
public class Assert {

    private static boolean areThreadAssertsEnabled = true;

    public static void setAreThreadAssertsEnabled(boolean areThreadAssertsEnabled) {
        Assert.areThreadAssertsEnabled = areThreadAssertsEnabled;
    }

    @Deprecated
    public static void fail() {
        throw new AssertionError("Fail");
    }

    /**
     * Called when a truly exceptional case occurs.
     *
     * @param reason
     */
    @Deprecated
    public static void fail(String reason) {
        throw new AssertionError(reason);
    }


    public static void checkArgument(boolean expression) {
        checkArgument(expression, null);
    }


    public static void checkArgument(
            boolean expression, @Nullable String messageTemplate, Object... args) {
        if (!expression) {
            throw new IllegalArgumentException(format(messageTemplate, args));
        }
    }


    public static void checkState(boolean expression) {
        checkState(expression, null);
    }


    public static void checkState(
            boolean expression, @Nullable String messageTemplate, Object... args) {
        if (!expression) {
            throw new IllegalStateException(format(messageTemplate, args));
        }
    }


    @NonNull
    public static <T> T isNotNull(@Nullable T reference) {
        return isNotNull(reference, null);
    }


    @NonNull
    public static <T> T isNotNull(
            @Nullable T reference, @Nullable String messageTemplate, Object... args) {
        if (reference == null) {
            throw new NullPointerException(format(messageTemplate, args));
        }
        return reference;
    }


    public static void isMainThread() {
        isMainThread(null);
    }


    public static void isMainThread(@Nullable String messageTemplate, Object... args) {
        if (!areThreadAssertsEnabled) {
            return;
        }
        checkState(Looper.getMainLooper().equals(Looper.myLooper()), messageTemplate, args);
    }


    public static void isWorkerThread() {
        isWorkerThread(null);
    }


    public static void isWorkerThread(@Nullable String messageTemplate, Object... args) {
        if (!areThreadAssertsEnabled) {
            return;
        }
        checkState(!Looper.getMainLooper().equals(Looper.myLooper()), messageTemplate, args);
    }

    private static String format(@Nullable String messageTemplate, Object... args) {
        if (messageTemplate == null) {
            return null;
        }
        return String.format(messageTemplate, args);
    }
}
